package geometry;

import ru.ts.gisutils.geometry.IXY;
import ru.ts.gisutils.geometry.IXYGeometry;
import ru.ts.gisutils.geometry.XYGeometry;
import ru.ts.gisutils.geometry.XY;

/**
 * Created by IntelliJ IDEA.
 * User: sigolaev_va
 * Date: 25.01.2013
 * Time: 15:27:31
 * To change this template use File | Settings | File Templates.
 */
public class XYLine implements IXYLine
{
  private IXY m_p1, m_p2;

  public static IXYGeometry g_geom = new XYGeometry();

  private XYLine()
  {
  }

  public XYLine( IXY p1, IXY p2 )
  {
    m_p1 = p1;
    m_p2 = p2;
  }

  public IXY startPoint()
  {
    return m_p1;
  }

  public IXY endPoint()
  {
    return m_p2;
  }

  public double distance( IXY point )
  {
    return g_geom.distance( m_p1, m_p2 );
  }

  public IXYLine connectLine( IXY pnt )
  {
    IXY resPnt = new XY( );
    double ret = g_geom.perpendicular( resPnt, pnt, m_p1, m_p2 );
    if ( ret < 0.0)
    {
      // intersection before p1
      return new XYLine( ((XY)pnt).copyOf(), ((XY)m_p1).copyOf() );
    }
    else if ( ret > 1.0)
    {
      // intersection after p2
      return new XYLine( ((XY)pnt).copyOf(), ((XY)m_p2).copyOf() );
    }
    // perpendicular point is the nearest one to the line
    return new XYLine( ((XY)pnt).copyOf(), resPnt);
  }

  public double length()
  {
    return g_geom.distance( m_p1, m_p2 );
  }
}